package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.IPushDaMaiApiService;
import com.block.datapush.service.apipush.utils.DaMaiHuaHuaApibAES;
import com.block.datapush.service.apipush.utils.DaMaiHuaHuaApibUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 大麦花花半流程
 */
@Service
public class DaMaiHuaHuaApiBRatePushApiService implements IPushDaMaiApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiCode = pushApiKeyParam.getApiCode();//source
        String apiKey = pushApiKeyParam.getApiKey();//AES加密密钥

        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();//小写


        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("md5Phone", mobileMd5);
        bizMap.put("ipaddress", DaMaiHuaHuaApibUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("loan", DaMaiHuaHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("loan_term", DaMaiHuaHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        bizMap.put("loan_use", DaMaiHuaHuaApibUtil.getLoanUse(memberSourceInfo.getYongtu()));
        bizMap.put("professional", DaMaiHuaHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("enterprise_type", 0);
        bizMap.put("monthly_income", DaMaiHuaHuaApibUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("salary_type", 1);
        bizMap.put("enterprise_flow", 0);
        bizMap.put("enterprise_license", 0);
        bizMap.put("education", DaMaiHuaHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("credit_history", DaMaiHuaHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));
        bizMap.put("zhima_credit", DaMaiHuaHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("social_security_and_accumulation_fund", DaMaiHuaHuaApibUtil.getShebaoAndGjj(memberSourceInfo.getShebao(), memberSourceInfo.getGjj()));
        bizMap.put("micro_loan", 2);
        bizMap.put("life_insurance", DaMaiHuaHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("house_property", DaMaiHuaHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car_property", DaMaiHuaHuaApibUtil.getCar(memberSourceInfo.getCar()));



        String encrypt = DaMaiHuaHuaApibAES.Encrypt(JSON.toJSONString(bizMap), apiKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("source", apiCode);
        paramMap.put("data", encrypt);

        log.info("【大麦花花半流程分润】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【大麦花花半流程分润】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean status = data.getBoolean("status");

            if (ObjectUtil.equal(status, true)) {

                String url = data.getString("url");
                pushApiResult.setPushSuccess(true);
                pushApiResult.setApproveUrl(url);
                pushApiResult.setOutOrderNo(mobileMd5);
                pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("mobileMd5",mobileMd5);
                pushApiResult.setExtJson(jsonObject);

                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    BigDecimal price = data.getBigDecimal("price");//下游返回分润前价格
                    if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceRight = typeRate.multiply(price);//分润后价格
                    pushApiResult.setPrice(price);
                    pushApiResult.setPriceRight(priceRight);
                }
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo,  String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();


        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("ipaddress", memberSourceInfo.getReqIp());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("loan", DaMaiHuaHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("loan_term", DaMaiHuaHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        bizMap.put("loan_use", DaMaiHuaHuaApibUtil.getLoanUse(memberSourceInfo.getYongtu()));
        bizMap.put("professional", DaMaiHuaHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("enterprise_type", 0);
        bizMap.put("monthly_income", DaMaiHuaHuaApibUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("salary_type", 1);
        bizMap.put("enterprise_flow", 0);
        bizMap.put("enterprise_license", 0);
        bizMap.put("education", DaMaiHuaHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("credit_history", DaMaiHuaHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));
        bizMap.put("zhima_credit", DaMaiHuaHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("social_security_and_accumulation_fund", DaMaiHuaHuaApibUtil.getShebaoAndGjj(memberSourceInfo.getShebao(), memberSourceInfo.getGjj()));
        bizMap.put("micro_loan", 2);
        bizMap.put("life_insurance", DaMaiHuaHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("house_property", DaMaiHuaHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car_property", DaMaiHuaHuaApibUtil.getCar(memberSourceInfo.getCar()));

        String encrypt = DaMaiHuaHuaApibAES.Encrypt(JSON.toJSONString(bizMap), pushApiKeyParam.getApiKey());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("source", pushApiKeyParam.getApiCode());
        paramMap.put("data", encrypt);


        log.info("【大麦花花半流程分润】导单开始【requestUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【大麦花花半流程分润】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean status = data.getBoolean("status");
            if (ObjectUtil.equal(status, true)) {
                String tid = data.getString("tid");
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(false);

                pushApiResult.setOutOrderNo(tid);
                pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
//        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
//
//        noticeParamDTO.setOutFlag(true);
//        noticeParamDTO.setSettleFlag(true);
//        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
//        noticeParamDTO.setQueryResult(paramContent);
//
//        JSONObject jsonObject = JSON.parseObject(paramContent);
//        if (ObjectUtil.isEmpty(jsonObject)){
//            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
//            return noticeParamDTO;
//        }
//        return noticeParamDTO;
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(false);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        JSONObject jsonObject = JSON.parseObject(paramContent);

        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }

        String md5Phone = jsonObject.getString("md5Phone");
        noticeParamDTO.setOrderNo(md5Phone);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId,md5Phone);

        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }

        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "success");
        return jsonObject;
    }
    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();

        paramResult.setFilePath("/priprotocol/damai");

        JSONObject userInfo = new JSONObject();
        userInfo.put("datetime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));
        userInfo.put("accountNo", memberSourceInfo.getMobile());
        userInfo.put("uid", String.valueOf(memberSourceInfo.getUid()));

        paramResult.setUserInfo(userInfo);

        return paramResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultDaMaiParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {

        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);

        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String tid = jsonObject.getString("tid");
        if (StrUtil.isEmpty(tid)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        noticeParamDTO.setOutOrderNo(tid);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(tid));

        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }

        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }
}
